package cz.cvut.fit.web.nakupniSeznam;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import cz.cvut.fit.web.nakupniSeznam.dao.UserDAO;
import cz.cvut.fit.web.nakupniSeznam.data.User;

public class KeyGenerator {
	public static final int KEY_LENGTH = 10;
	
	private String key;
	private String alphabet;

	public KeyGenerator() {
		super();
		this.key = "";
		this.alphabet = "ABCDEFGHJKLMNOPQRSTUV123456789";
	}
	
	public String generateKey(){
		List<User> users = UserDAO.getInstance().getAll();
		List<String> usersKeys = new ArrayList<String>();
				
		for(User u : users) {
			usersKeys.add(u.getKey());
		}
	
		Random r = new Random();
		do {
			key = "";
			for(int i =0; i< KeyGenerator.KEY_LENGTH; i++) {
				
				key += alphabet.charAt(r.nextInt(alphabet.length()));
			}
			
		}
		//controls if there is user with such a key in DB already
		while(Collections.binarySearch(usersKeys, key) >=0);
		
		return key;
	}
	

}
